package Presentacion;

import Clases.Empleado;
import Clases.Vacacion;
import Clases.VacacionPagada;
import Control.ControlEmpleado;
import Control.ControlPago;
import Control.ControlVacaciones;
import Control.ControlVacacionesPagadas;
import de.javasoft.plaf.synthetica.SyntheticaLookAndFeel;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class ManejoVacacionesPagadas extends javax.swing.JFrame {

    private ImageIcon iconoError;
    ControlPago controlP = ControlPago.obtenerInstancia();
    ControlEmpleado controlE = ControlEmpleado.obtenerInstancia();
    ControlVacacionesPagadas controlVP = ControlVacacionesPagadas.obtenerInstancia();
    ControlVacaciones controlV = controlV = ControlVacaciones.obtenerInstancia();
    NumberFormat numberFormat = (DecimalFormat) DecimalFormat.getNumberInstance();

    public ManejoVacacionesPagadas() {
        initComponents();
        inicioTooltops();
    }

    private static ManejoVacacionesPagadas instancia = null;

    public static ManejoVacacionesPagadas obtenerInstancia() {
        if (instancia == null) {
            instancia = new ManejoVacacionesPagadas();
        }
        return instancia;
    }

    private void ocultarLabels() {

        labelVacacionesRestantes.setVisible(false);
        labelCantidadDias.setVisible(false);

    }

    private void inicioTooltops() {
        iconoError = new ImageIcon(getClass().getResource("/Imagenes/warning.png"));

        labelVacacionesRestantes.setIcon(iconoError);
        labelVacacionesRestantes.setToolTipText("No le quedan vacaciones restantes");

        labelCantidadDias.setIcon(iconoError);
        labelCantidadDias.setToolTipText("Ingrese un número menor a la cantidad de vacaciones restantes");

        ocultarLabels();
    }

    public void init(String cedula, String nombre) {
        setTitle(" Asignación de Vacaciones pagadas");
        setLocationRelativeTo(null);
        UIManager.removeAuxiliaryLookAndFeel(UIManager.getLookAndFeel());
        SwingUtilities.updateComponentTreeUI(this);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        try {
            UIManager.removeAuxiliaryLookAndFeel(UIManager.getLookAndFeel());
            SyntheticaLookAndFeel.setWindowsDecorated(false);
            UIManager.setLookAndFeel("de.javasoft.plaf.synthetica.SyntheticaAluOxideLookAndFeel");
            SwingUtilities.updateComponentTreeUI(this);

        } catch (Exception ex) {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        this.setVisible(true);
        this.ocultarLabels();
        limpiar();
        setJLabels(cedula, nombre);

    }

    void setJLabels(String cedulaEmpleado, String nombre) {
        this.labelCedula.setText(cedulaEmpleado);
        this.labelNombre.setText(nombre);
        Empleado e = controlE.getEmpleadoCedula(Long.parseLong(cedulaEmpleado));
        this.labelVacaciones.setText(String.valueOf(calcularVacaciones(e.getFechaInicio(), e.getNumEmpleado())));
        this.labelCodigo.setText(String.valueOf(e.getCodigo()));

    }

    public void limpiar() {
        labelCedula.setText("________________");
        labelNombre.setText("________________");
        labelCodigo.setText("________________");
        labelVacaciones.setText("________________");
        jTextField2.setText("");
        this.ocultarLabels();

    }

    boolean validarVacacion() {
        boolean itsk = true;

        if (Integer.parseInt(labelVacaciones.getText()) <= 0) {
            labelVacacionesRestantes.setVisible(true);
            itsk = false;
        }
        if (jTextField2.getText().equals("")) {
            labelVacacionesRestantes.setVisible(true);
            itsk = false;
        } else {
            double porPagar;
            try {
                porPagar = jTextField2.getText().trim().isEmpty() ? null : numberFormat.parse(jTextField2.getText()).doubleValue();
                if (porPagar <= 0 || porPagar > Double.valueOf(labelVacaciones.getText())) {
                    labelVacacionesRestantes.setVisible(true);
                    itsk = false;
                }
            } catch (ParseException ex) {
                Logger.getLogger(ManejoVacacionesPagadas.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        return itsk;
    }

    int calcularVacaciones(Date inicio, Long numEmpleado) {
        Date actual = new Date();
        int totalVacaciones = 0;
        int anioInicio = inicio.getYear();
        int anioActual = actual.getYear();
        int diaInicio = inicio.getDate();
        int diaActual = actual.getDate();
        int mesActual = actual.getMonth();
        int mesInicio = inicio.getMonth();
        if (anioInicio < anioActual) {
            mesInicio = 0;
            if (diaInicio <= diaActual) {
                mesInicio = 0;
                totalVacaciones = mesActual - mesInicio;
            } else if (diaInicio > diaActual) {

                totalVacaciones = mesActual - mesInicio - 1;

            }
        } else if (anioInicio == anioActual) {
            if (mesInicio == mesActual) {
                totalVacaciones = 0;
            } else if (mesInicio <= mesActual) {
                if (diaInicio > diaActual) {
                    totalVacaciones = mesActual - mesInicio - 1;
                } else if (diaInicio <= diaActual) {
                    totalVacaciones = mesActual - mesInicio;
                }

            }
        } else {
            JOptionPane.showMessageDialog(null, "La fecha de inicio es mayor a la fecha actual", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
        }
        List<Vacacion> vacaciones = controlV.getVacacionesPorNumEmpleado(numEmpleado);

        List<VacacionPagada> vacacionesP = controlVP.getVacacionesPorNumEmpleado(numEmpleado);

        if (!vacaciones.isEmpty()) {
            totalVacaciones = totalVacaciones - vacaciones.size();
        }
        if (!vacacionesP.isEmpty()) {
            totalVacaciones = totalVacaciones - vacacionesP.size();
        }

        return totalVacaciones;
    }
    void crear(){
     ocultarLabels();
        boolean error = validarVacacion();
        if (error == true) {
            int maximo=Integer.valueOf(jTextField2.getText());
            for(int i=0;i<maximo;i++){
            Long cedula = Long.valueOf(labelCedula.getText());
            Empleado empleado = controlE.getEmpleadoCedula(cedula);
            
            VacacionPagada vp = new VacacionPagada(empleado, controlP.getPago().get(1));

            boolean inserto = controlVP.insertarVacaciones(vp);
            if (!inserto) {
                JOptionPane.showMessageDialog(null, "No se pudo insertar la vacación", "Mensaje", JOptionPane.ERROR_MESSAGE);
            } else {
                //JOptionPane.showMessageDialog(null, "Vacación ingresada con éxito", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                ManejoVacaciones vacaciones=ManejoVacaciones.obtenerInstancia();
                String vacacionesRest=String.valueOf(Integer.valueOf(labelVacaciones.getText())-Integer.valueOf(jTextField2.getText()));
                vacaciones.setLabelsPagada(vacacionesRest, Integer.valueOf(jTextField2.getText()));
                dispose();
                if(i==0){
                 JOptionPane.showMessageDialog(null, "Vacación ingresada con éxito", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                }
            }
            
            }

        }
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        labelVacacionesRestantes = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        labelCantidadDias = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        labelNombre = new javax.swing.JLabel();
        labelCedula = new javax.swing.JLabel();
        labelVacaciones = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        labelCodigo = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(440, 280));
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setText("Pagar Vacaciones");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel2.setText("Cédula de empleado: ");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel3.setText("Vacaciones restantes:");

        jButton2.setText("Asignar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Salir");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        labelVacacionesRestantes.setText("x");
        labelVacacionesRestantes.setMaximumSize(new java.awt.Dimension(24, 24));
        labelVacacionesRestantes.setMinimumSize(new java.awt.Dimension(22, 22));
        labelVacacionesRestantes.setPreferredSize(new java.awt.Dimension(22, 22));

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel4.setText("Cantidad de dias:");

        jTextField2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextField2KeyPressed(evt);
            }
        });

        labelCantidadDias.setText("x");
        labelCantidadDias.setMaximumSize(new java.awt.Dimension(22, 22));
        labelCantidadDias.setMinimumSize(new java.awt.Dimension(22, 22));
        labelCantidadDias.setPreferredSize(new java.awt.Dimension(22, 22));

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel5.setText("Nombre de empleado:");

        labelNombre.setText("________________");

        labelCedula.setText("________________");

        labelVacaciones.setText("________________");

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel6.setText("Código de empleado:");

        labelCodigo.setText("________________");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel6)
                                    .addComponent(jLabel5)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4)))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(33, 33, 33)
                                .addComponent(jLabel2)
                                .addGap(2, 2, 2)))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(50, 50, 50)
                                .addComponent(jButton2)
                                .addGap(18, 18, 18)
                                .addComponent(jButton3))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(labelCedula, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(labelVacaciones, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(labelVacacionesRestantes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(labelCantidadDias, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(labelCodigo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(labelNombre, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE))))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(92, 92, 92)
                        .addComponent(jLabel1)))
                .addContainerGap(61, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(24, 24, 24)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(labelCedula))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton2)
                            .addComponent(jButton3))
                        .addGap(19, 19, 19))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(18, 18, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(labelCodigo))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(labelNombre))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(labelVacaciones)
                            .addComponent(labelVacacionesRestantes, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(labelCantidadDias, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(57, 57, 57))))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.crear();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jTextField2KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField2KeyPressed
         int key = evt.getKeyCode();
        if (key == evt.VK_ENTER) {
            this.crear();
        }
    }//GEN-LAST:event_jTextField2KeyPressed

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ManejoVacacionesPagadas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ManejoVacacionesPagadas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ManejoVacacionesPagadas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ManejoVacacionesPagadas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ManejoVacacionesPagadas().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JLabel labelCantidadDias;
    private javax.swing.JLabel labelCedula;
    private javax.swing.JLabel labelCodigo;
    private javax.swing.JLabel labelNombre;
    private javax.swing.JLabel labelVacaciones;
    private javax.swing.JLabel labelVacacionesRestantes;
    // End of variables declaration//GEN-END:variables
}
